<template>
  <div>
    <van-nav-bar title="密码登录" left-arrow @click-left="$router.back()" />
    <form autocomplete="on">
      <van-cell-group>
        <van-field v-model="username" required label="账号" placeholder="请输入账号" autocomplete />
        <van-field
          v-model="password"
          type="password"
          required
          label="密码"
          placeholder="请输入密码"
          autocomplete
        />
        <van-row>
          <van-col span="14">
            <van-field v-model="captchas" label="验证码" placeholder="请输入验证码" required />
          </van-col>
          <van-col span="5">
            <img :src="imgUrl" />
          </van-col>
          <van-col span="5" class="sms_text">
            <span>看不清</span>
            <span style="color:#3b95e9" @click="getCaptchas">换一张</span>
          </van-col>
        </van-row>
      </van-cell-group>
      <van-row>
        <van-col span="24">
          <van-button type="info" @click="login">登录/注册</van-button>
        </van-col>
      </van-row>
    </form>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "login",
  data() {
    return {
      username: "",
      password: "",
      captchas: "",
      imgUrl: "",
    };
  },
  computed: {
    ...mapState(["geohash"]),
  },
  methods: {
    async getCaptchas() {
      //获取验证码
      const { data: res } = await this.$axios.post("v1/captchas");
      if (res.status == 1) {
        this.imgUrl = res.code;
      } else {
        this.$notify({ type: "danger", message: "获取失败" });
      }
    },
    async login() {
      //登录
      // let sha1 = require("js-sha1"); //密码加密
      if (
        this.username !== "" &&
        this.password !== "" &&
        this.captchas !== ""
      ) {
        const { data: res } = await this.$axios.post(
          "https://elm.cangdu.org/v2/login",
          {
            username: this.username,
            // password: sha1(this.password),
            password: this.password,
            captcha_code: this.captchas,
          }
        );
        if (res.status == 0) {
          this.getCaptchas();
          this.$toast(res.message);
        } else {
          this.$store.commit("setUser", res);
          window.console.log(this.$router);
          const redirect = this.$route.query.redirect;
          if (redirect) {
            this.$router.replace(redirect);
          } else {
            this.$router.push(`/msite?geohash=${this.geohash}`);
          }
        }
      }
    },
  },
  mounted() {
    this.getCaptchas();
  },
};
</script>

<style lang="stylus" scoped>
.van-cell--required::before {
  left: 2px;
}

.sms_text {
  display: flex;
  padding: 10px;
  flex-direction: column;
  font-size: 14px;
}

.van-button {
  width: 100%;
}
</style>